let originalWX = wx

let promisify = func => args => new Promise((resolve, reject) => {
  func(Object.assign(args, {
      success: resolve,
      fail: reject,
  }))
})

let hasCallback = obj => {
    let cbs = ['success', 'fail', 'complete']
    return Object.keys(obj).some(k => cbs.includes(k))
}

let syncFuncList = ['getMenuButtonBoundingClientRect']

let promisify_wx = new Proxy({}, {
    get(target, name) {
        if (name in originalWX ) {
            let fn = originalWX[name]
            let isSyncFunc = name.endsWith('Sync') || syncFuncList.includes(name) // 同步函数 
            let isNotFunc = typeof fn !== 'function' // 非函数

            if (isSyncFunc || isNotFunc) return fn

            return (obj) => {
                if (!obj) return fn()
                if (hasCallback(obj)) return fn(obj)
                return promisify(fn)(obj)
            }
        }
    }
});

export {promisify_wx};